<template>
  <view class="electricity-calc">
    <view class="calc-section">
      <view class="section-title">电费预估</view>
      <view class="card-list">
        <!-- 单一电价卡片 -->
        <view class="calc-card" :class="{ active: activeSingle }">
          <view class="card-header" @click="toggleCard('single')">
            <image
              class="card-icon"
              src="/static/img/components/card-icon-1.png"
              mode="widthFix"
            ></image>
            <text class="card-title">单一电价</text>
            <image
              class="card-arrow"
              :src="
                activeSingle
                  ? '/static/img/components/arrow-up.png'
                  : '/static/img/components/arrow-down.png'
              "
              mode="widthFix"
            />
          </view>
            <view class="card-body" :class="{ collapsed: !activeSingle }">
              <!-- 电价输入 -->
              <view class="price-input-section">
                <text class="price-label">电价 (元/千瓦时)</text>
                <input
                  v-model="singlePrice"
                  type="number"
                  min="0"
                  placeholder="例如：0.65"
                  class="price-input"
                />
              </view>

              <!-- 日期区间选择 -->
              <view class="date-range-section">
                <view class="date-input-group">
                  <text
                    class="date-input"
                    @click="openDatePicker('single', 'start')"
                  >
                    {{ singleDateStart || '开始日期' }}
                  </text>
                  <image
                    class="calendar-icon"
                    src="/static/img/components/calendar-icon.png"
                    mode="widthFix"
                  />
                </view>
                <view class="date-input-group">
                  <text
                    class="date-input"
                    @click="openDatePicker('single', 'end')"
                  >
                    {{ singleDateEnd || '结束日期' }}
                  </text>
                  <image
                    class="calendar-icon"
                    src="/static/img/components/calendar-icon.png"
                    mode="widthFix"
                  />
                </view>
              </view>
            </view>
        </view>
        <!-- 峰谷电价卡片 -->
        <view class="calc-card" :class="{ active: activePeakvalley }">
          <view class="card-header" @click="toggleCard('peakvalley')">
            <image
              class="card-icon"
              src="/static/img/components/card-icon-2.png"
              mode="widthFix"
            ></image>
            <text class="card-title">峰谷电价</text>
            <image
              class="card-arrow"
              :src="
                activePeakvalley
                  ? '/static/img/components/arrow-up.png'
                  : '/static/img/components/arrow-down.png'
              "
              mode="widthFix"
            />
          </view>
            <view class="card-body" :class="{ collapsed: !activePeakvalley }">
              <!-- 峰值电价区域 -->
              <view class="peak-price-section">
                <text class="price-label">峰值电价 (元/千瓦时)</text>
                <input
                  v-model="peakPrice"
                  type="number"
                  min="0"
                  placeholder="例如: 0.65"
                  class="price-input"
                />

                <!-- 峰值时段选择 -->
                <view class="time-range-section">
                  <view class="time-input-group">
                    <text
                      class="time-input"
                      @click="openTimePicker('peak', 'start')"
                    >
                      {{ peakStartTime || '开始时间' }}
                    </text>
                    <image
                      class="time-icon"
                      src="/static/img/components/clock-icon.png"
                      mode="widthFix"
                    />
                  </view>
                  <view class="time-input-group">
                    <text
                      class="time-input"
                      @click="openTimePicker('peak', 'end')"
                    >
                      {{ peakEndTime || '结束时间' }}
                    </text>
                    <image
                      class="time-icon"
                      src="/static/img/components/clock-icon.png"
                      mode="widthFix"
                    />
                  </view>
                </view>
              </view>

              <!-- 谷值电价区域 -->
              <view>
                <text class="price-label">谷值电价 (元/千瓦时)</text>
                <input
                  v-model="offPeakPrice"
                  type="number"
                  min="0"
                  placeholder="例如: 0.65"
                  class="price-input"
                />

                <!-- 谷值时段选择 -->
                <view class="time-range-section last-time-section">
                  <view class="time-input-group">
                    <text
                      class="time-input"
                      @click="openTimePicker('offPeak', 'start')"
                    >
                      {{ offPeakStartTime || '开始时间' }}
                    </text>
                    <image
                      class="time-icon"
                      src="/static/img/components/clock-icon.png"
                      mode="widthFix"
                    />
                  </view>
                  <view class="time-input-group">
                    <text
                      class="time-input"
                      @click="openTimePicker('offPeak', 'end')"
                    >
                      {{ offPeakEndTime || '结束时间' }}
                    </text>
                    <image
                      class="time-icon"
                      src="/static/img/components/clock-icon.png"
                      mode="widthFix"
                    />
                  </view>
                </view>

                <!-- 日期区间选择 -->
                <view class="date-range-section">
                  <view class="date-input-group">
                    <text
                      class="date-input"
                      @click="openDatePicker('peakvalley', 'start')"
                    >
                      {{ peakvalleyDateStart || '开始日期' }}
                    </text>
                    <image
                      class="calendar-icon"
                      src="/static/img/components/calendar-icon.png"
                      mode="widthFix"
                    />
                  </view>
                  <view class="date-input-group">
                    <text
                      class="date-input"
                      @click="openDatePicker('peakvalley', 'end')"
                    >
                      {{ peakvalleyDateEnd || '结束日期' }}
                    </text>
                    <image
                      class="calendar-icon"
                      src="/static/img/components/calendar-icon.png"
                      mode="widthFix"
                    />
                  </view>
                </view>
              </view>
            </view>
        </view>
        <!-- 阶梯电价卡片 -->
        <view class="calc-card" :class="{ active: activeLadder }">
          <view class="card-header" @click="toggleCard('ladder')">
            <image
              class="card-icon"
              src="/static/img/components/card-icon-3.png"
              mode="widthFix"
            ></image>
            <text class="card-title">阶梯电价</text>
            <image
              class="card-arrow"
              :src="
                activeLadder
                  ? '/static/img/components/arrow-up.png'
                  : '/static/img/components/arrow-down.png'
              "
              mode="widthFix"
            />
          </view>
            <view class="card-body" :class="{ collapsed: !activeLadder }">
              <view class="ladder-row">
                <text class="ladder-label">第一阶梯：</text>
                <input
                  v-model="ladder1Limit"
                  type="number"
                  min="0"
                  placeholder="用电量上限"
                  class="ladder-input"
                />
                <input
                  v-model="ladder1Price"
                  type="number"
                  min="0"
                  placeholder="电价"
                  class="ladder-input"
                />
              </view>
              <view class="ladder-row">
                <text class="ladder-label">第二阶梯：</text>
                <input
                  v-model="ladder2Limit"
                  type="number"
                  min="0"
                  placeholder="用电量上限"
                  class="ladder-input"
                />
                <input
                  v-model="ladder2Price"
                  type="number"
                  min="0"
                  placeholder="电价"
                  class="ladder-input"
                />
              </view>
              <view class="ladder-row">
                <text class="ladder-label">第三阶梯：</text>
                <input
                  v-model="ladder3Price"
                  type="number"
                  min="0"
                  placeholder="电价"
                  class="ladder-input"
                />
              </view>
              <!-- 日期区间选择 -->
              <view class="date-range-section">
                <view class="date-input-group">
                  <text
                    class="date-input"
                    @click="openDatePicker('ladder', 'start')"
                  >
                    {{ ladderDateStart || '开始日期' }}
                  </text>
                  <image
                    class="calendar-icon"
                    src="/static/img/components/calendar-icon.png"
                    mode="widthFix"
                  />
                </view>
                <view class="date-input-group">
                  <text
                    class="date-input"
                    @click="openDatePicker('ladder', 'end')"
                  >
                    {{ ladderDateEnd || '结束日期' }}
                  </text>
                  <image
                    class="calendar-icon"
                    src="/static/img/components/calendar-icon.png"
                    mode="widthFix"
                  />
                </view>
              </view>
            </view>
        </view>
        <view class="calc-button" @click="calculate">计算电费</view>
        <image
          class="table-bottom"
          src="/static/img/components/table-bottom.png"
          mode="widthFix"
        ></image>
      </view>
    </view>
    <!-- 计算结果弹窗 -->
    <view v-if="showResult" class="result-modal-mask">
      <view class="result-modal">
        <view class="result-icon-container">
          <image 
            class="result-icon-glow" 
            src="/static/img/components/result-icon-light.png" 
            mode="widthFix"
          />
        </view>
        <view class="result-content">
          <view class="result-main-text">该时段电费预测大约为</view>
          <view class="result-amount">{{ resultFee }}元</view>
          <view class="result-detail-text">
            <text>如果您使用智能电表，{{ selectedPeriodText }}时段电费大概是
            {{ smartMeterFee }}元
            ，请确保有足够的余额。</text>
          </view>
        </view>
        <view class="result-btn" @click="showResult = false">确定</view>
      </view>
    </view>
    <!-- 用电趋势图部分 -->
    <view class="section-title-chart">
      <text class="chart-title-text">用电趋势</text>
    </view>
    <view class="trend-section">
      <view class="chart-header-container">
        <view class="chart-header-title legend-text">用电量（kwh）</view>
        <!-- 图例 -->
        <view class="chart-legend">
          <view class="legend-item">
            <view class="legend-color"></view>
            <text class="legend-text">实际用电量 (kwh)</text>
          </view>
        </view>
      </view>
      <!-- 使用 swiper 包装图表 -->
      <tn-swiper
        v-model="currentSwiperIndex"
        :data="chartDataList"
        :height="swiperHeight + 'rpx'"
        :indicator="false"
        :autoplay="false"
        :loop="false"
        @change="handleSwiperChange"
      >
        <template #default="{ data: chartData, index: chartIndex }">
          <view class="chart-item">
            <!-- 图表 -->
            <view class="chart-container">
              <view v-if="isLoading" class="no-data-tip">
                <text class="no-data-text">数据加载中...</text>
              </view>
              <view v-else-if="chartData.categories.length === 0" class="no-data-tip">
                <text class="no-data-text">暂无数据</text>
              </view>
              <qiun-data-charts
                v-else
                type="line"
                :opts="chartData.chartOpts || getChartOpts(chartData.colors)"
                :chartData="chartData"
                :animation="false"
              />
            </view>
          </view>
        </template>
      </tn-swiper>
      <!-- 时间选择器 -->
      <view class="time-selector">
        <view
          v-for="(period, index) in timePeriods"
          :key="period.key"
          :class="['time-tab', { active: selectedPeriod === index }]"
          @click="handlePeriodChangeUpdated(index)"
        >
          <text class="time-text">{{ period.name }}</text>
        </view>
      </view>
    </view>
    <tn-popup v-model="showDatePicker" open-direction="bottom">
      <tn-calendar
        v-model="tempDate"
        :min-date="tempMinDate"
        :max-date="tempMaxDate"
        @change="onDateConfirm"
        class="detail-calendar"
        active-bg-color="#1ec8e1"
        active-text-color="#fff"
      />
    </tn-popup>
    
    <!-- 时间选择器 -->
    <tn-date-time-picker
      v-model="tempTime"
      v-model:open="showTimePicker"
      mode="timeNoSecond"
      format="HH:mm"
      :showCancel="false"
      @confirm="onTimeConfirm"
      confirm-color="#eee"
    />
  </view>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { createRequest } from '@/utils/request';

// 互斥展开逻辑（三个卡片之间都是互斥的）
const activeSingle = ref(true);
const activePeakvalley = ref(false);
const activeLadder = ref(false);
function toggleCard(type) {
  if (type === 'single') {
    const wasActive = activeSingle.value;
    activeSingle.value = !activeSingle.value;
    if (activeSingle.value) {
      closePeakvalleyCard();
      closeLadderCard();
    } else if (wasActive) {
      clearSingleInputs();
    }
  } else if (type === 'peakvalley') {
    const wasActive = activePeakvalley.value;
    activePeakvalley.value = !activePeakvalley.value;
    if (activePeakvalley.value) {
      closeSingleCard();
      closeLadderCard();
    } else if (wasActive) {
      clearPeakvalleyInputs();
    }
  } else if (type === 'ladder') {
    const wasActive = activeLadder.value;
    activeLadder.value = !activeLadder.value;
    if (activeLadder.value) {
      closeSingleCard();
      closePeakvalleyCard();
    } else if (wasActive) {
      clearLadderInputs();
    }
  }
}
function closeSingleCard() {
  if (activeSingle.value) {
    activeSingle.value = false;
    clearSingleInputs();
  }
}
function closePeakvalleyCard() {
  if (activePeakvalley.value) {
    activePeakvalley.value = false;
    clearPeakvalleyInputs();
  }
}
function closeLadderCard() {
  if (activeLadder.value) {
    activeLadder.value = false;
    clearLadderInputs();
  }
}
// 清空单一电价输入
function clearSingleInputs() {
  singlePrice.value = '';
  singleDateStart.value = '';
  singleDateEnd.value = '';
}
// 清空峰谷电价输入
function clearPeakvalleyInputs() {
  peakPrice.value = '';
  peakStartTime.value = '';
  peakEndTime.value = '';
  offPeakPrice.value = '';
  offPeakStartTime.value = '';
  offPeakEndTime.value = '';
  peakvalleyDateStart.value = '';
  peakvalleyDateEnd.value = '';
}
// 清空阶梯电价输入
function clearLadderInputs() {
  ladder1Limit.value = '';
  ladder1Price.value = '';
  ladder2Limit.value = '';
  ladder2Price.value = '';
  ladder3Price.value = '';
  ladderDateStart.value = '';
  ladderDateEnd.value = '';
}
// 表单数据
const singlePrice = ref('');
const singleDateStart = ref('');
const singleDateEnd = ref('');
const peakPrice = ref('');
const peakStartTime = ref('');
const peakEndTime = ref('');
const offPeakPrice = ref('');
const offPeakStartTime = ref('');
const offPeakEndTime = ref('');
const peakvalleyDateStart = ref('');
const peakvalleyDateEnd = ref('');
const ladder1Limit = ref('');
const ladder1Price = ref('');
const ladder2Limit = ref('');
const ladder2Price = ref('');
const ladder3Price = ref('');
const ladderDateStart = ref('');
const ladderDateEnd = ref('');
// 计算结果弹窗
const showResult = ref(false);
const resultFee = ref('568.23');
const smartMeterFee = ref('520.15');

// 计算当前选中的时间段文本
const selectedPeriodText = computed(() => {
  return timePeriods[selectedPeriod.value]?.name || '当前';
});

function isValidPeriod(period) {
  return /^\d{2}:\d{2}~\d{2}:\d{2}$/.test(period);
}

// 将时间字符串转换为分钟数
function timeToMinutes(timeStr) {
  const [hours, minutes] = timeStr.split(':').map(Number);
  return hours * 60 + minutes;
}

// 日期格式转换函数：将 YYYY-MM-DD 转换为 YYYY-MM-DD HH:mm:ss
function formatDateForApi(dateStr, isStart = true) {
  if (!dateStr) return '';
  // 确保日期格式为 YYYY-MM-DD
  const formattedDate = dateStr.replace(/\//g, '-');
  // 根据是开始时间还是结束时间添加对应的时间
  const time = isStart ? '00:00:00' : '23:59:59';
  return `${formattedDate} ${time}`;
}

// 检查两个时间段是否重叠
function isOverlapping(start1, end1, start2, end2) {
  // 处理跨天的情况
  const dayMinutes = 24 * 60;
  
  // 标准化时间到同一天
  const s1 = start1 < end1 ? start1 : start1 - dayMinutes;
  const e1 = start1 < end1 ? end1 : end1 + dayMinutes;
  const s2 = start2 < end2 ? start2 : start2 - dayMinutes;
  const e2 = start2 < end2 ? end2 : end2 + dayMinutes;
  
  // 检查是否重叠
  return !(e1 <= s2 || e2 <= s1);
}

function checkPeriods(peakPeriod, offPeakPeriod) {
  if (!isValidPeriod(peakPeriod) || !isValidPeriod(offPeakPeriod)) {
    uni.showToast({ title: '时段格式错误，应为HH:MM~HH:MM', icon: 'none' });
    return false;
  }
  
  const [peakStart, peakEnd] = peakPeriod.split('~');
  const [offStart, offEnd] = offPeakPeriod.split('~');
  
  // 转换为分钟数
  const peakStartMin = timeToMinutes(peakStart);
  const peakEndMin = timeToMinutes(peakEnd);
  const offStartMin = timeToMinutes(offStart);
  const offEndMin = timeToMinutes(offEnd);
  
  // 检查时段是否重叠
  if (isOverlapping(peakStartMin, peakEndMin, offStartMin, offEndMin)) {
    uni.showToast({ title: '峰谷时段不能重叠', icon: 'none' });
    return false;
  }
  
  // 计算各时段时长
  const peakDuration = peakEndMin >= peakStartMin ? 
    peakEndMin - peakStartMin : 
    (24 * 60 - peakStartMin) + peakEndMin;
  
  const offPeakDuration = offEndMin >= offStartMin ? 
    offEndMin - offStartMin : 
    (24 * 60 - offStartMin) + offEndMin;
  
  // 检查总时长是否为24小时
  const totalDuration = peakDuration + offPeakDuration;
  if (totalDuration !== 24 * 60) {
    uni.showToast({ title: '峰谷时段总时长必须为24小时', icon: 'none' });
    return false;
  }
  
  return true;
}

async function calculate() {
  // 1. 校验输入完整性
  let type = '';
  let data = {};
  
  if (activeSingle.value) {
    // 单一电价验证
    if (singlePrice.value === '') {
      uni.showToast({ title: '请输入单一电价', icon: 'none' });
      return;
    }
    if (singleDateStart.value === '') {
      uni.showToast({ title: '请选择开始日期', icon: 'none' });
      return;
    }
    if (singleDateEnd.value === '') {
      uni.showToast({ title: '请选择结束日期', icon: 'none' });
      return;
    }
    
    // 价格合理性验证
    const singlePriceValue = parseFloat(singlePrice.value);
    if (isNaN(singlePriceValue) || singlePriceValue <= 0) {
      uni.showToast({ title: '电价必须大于0', icon: 'none' });
      return;
    }
    if (singlePriceValue > 10) {
      uni.showToast({ title: '电价不能超过10元/千瓦时', icon: 'none' });
      return;
    }
    
    // 日期先后顺序验证
    if (singleDateStart.value >= singleDateEnd.value) {
      uni.showToast({ title: '开始日期必须早于结束日期', icon: 'none' });
      return;
    }
    
    type = 'single';
    data = {
      type,
      price: singlePrice.value,
      dateStart: singleDateStart.value,
      dateEnd: singleDateEnd.value,
    };
  } else if (activePeakvalley.value) {
    // 峰谷电价验证
    if (peakPrice.value === '') {
      uni.showToast({ title: '请输入峰值电价', icon: 'none' });
      return;
    }
    if (offPeakPrice.value === '') {
      uni.showToast({ title: '请输入谷值电价', icon: 'none' });
      return;
    }
    if (peakStartTime.value === '' || peakEndTime.value === '') {
      uni.showToast({ title: '请选择峰值时段', icon: 'none' });
      return;
    }
    if (offPeakStartTime.value === '' || offPeakEndTime.value === '') {
      uni.showToast({ title: '请选择谷值时段', icon: 'none' });
      return;
    }
    if (peakvalleyDateStart.value === '') {
      uni.showToast({ title: '请选择开始日期', icon: 'none' });
      return;
    }
    if (peakvalleyDateEnd.value === '') {
      uni.showToast({ title: '请选择结束日期', icon: 'none' });
      return;
    }
    
    // 价格合理性验证
    const peakPriceValue = parseFloat(peakPrice.value);
    const offPeakPriceValue = parseFloat(offPeakPrice.value);
    if (isNaN(peakPriceValue) || peakPriceValue <= 0) {
      uni.showToast({ title: '峰值电价必须大于0', icon: 'none' });
      return;
    }
    if (isNaN(offPeakPriceValue) || offPeakPriceValue <= 0) {
      uni.showToast({ title: '谷值电价必须大于0', icon: 'none' });
      return;
    }
    if (peakPriceValue <= offPeakPriceValue) {
      uni.showToast({ title: '峰值电价必须高于谷值电价', icon: 'none' });
      return;
    }
    
    // 日期先后顺序验证
    if (peakvalleyDateStart.value >= peakvalleyDateEnd.value) {
      uni.showToast({ title: '开始日期必须早于结束日期', icon: 'none' });
      return;
    }
    
    // 峰谷时段校验
    const peakPeriod = `${peakStartTime.value}~${peakEndTime.value}`;
    const offPeakPeriod = `${offPeakStartTime.value}~${offPeakEndTime.value}`;
    if (!checkPeriods(peakPeriod, offPeakPeriod)) {
      return;
    }
    
    type = 'peakvalley';
    data = {
      type,
      peakPrice: peakPrice.value,
      offPeakPrice: offPeakPrice.value,
      peakPeriod: `${peakStartTime.value}~${peakEndTime.value}`,
      offPeakPeriod: `${offPeakStartTime.value}~${offPeakEndTime.value}`,
      dateStart: peakvalleyDateStart.value,
      dateEnd: peakvalleyDateEnd.value,
    };
  } else if (activeLadder.value) {
    // 阶梯电价验证
    if (ladder1Limit.value === '') {
      uni.showToast({ title: '请输入第一阶梯用电量上限', icon: 'none' });
      return;
    }
    if (ladder1Price.value === '') {
      uni.showToast({ title: '请输入第一阶梯电价', icon: 'none' });
      return;
    }
    if (ladder2Price.value === '') {
      uni.showToast({ title: '请输入第二阶梯电价', icon: 'none' });
      return;
    }
    if (ladder3Price.value === '') {
      uni.showToast({ title: '请输入第三阶梯电价', icon: 'none' });
      return;
    }
    if (ladderDateStart.value === '') {
      uni.showToast({ title: '请选择开始日期', icon: 'none' });
      return;
    }
    if (ladderDateEnd.value === '') {
      uni.showToast({ title: '请选择结束日期', icon: 'none' });
      return;
    }
    
    // 价格合理性验证
    const ladder1PriceValue = parseFloat(ladder1Price.value);
    const ladder2PriceValue = parseFloat(ladder2Price.value);
    const ladder3PriceValue = parseFloat(ladder3Price.value);
    if (isNaN(ladder1PriceValue) || ladder1PriceValue <= 0) {
      uni.showToast({ title: '第一阶梯电价必须大于0', icon: 'none' });
      return;
    }
    if (isNaN(ladder2PriceValue) || ladder2PriceValue <= 0) {
      uni.showToast({ title: '第二阶梯电价必须大于0', icon: 'none' });
      return;
    }
    if (isNaN(ladder3PriceValue) || ladder3PriceValue <= 0) {
      uni.showToast({ title: '第三阶梯电价必须大于0', icon: 'none' });
      return;
    }   
    // 阶梯电价逻辑验证
    if (ladder1PriceValue >= ladder2PriceValue) {
      uni.showToast({ title: '第二阶梯电价必须高于第一阶梯电价', icon: 'none' });
      return;
    }
    if (ladder2PriceValue >= ladder3PriceValue) {
      uni.showToast({ title: '第三阶梯电价必须高于第二阶梯电价', icon: 'none' });
      return;
    }
    
    // 用电量上限验证
    const ladder1LimitValue = parseFloat(ladder1Limit.value);
    if (isNaN(ladder1LimitValue) || ladder1LimitValue <= 0) {
      uni.showToast({ title: '第一阶梯用电量上限必须大于0', icon: 'none' });
      return;
    }
    
    // 第二阶梯用电量上限验证（可选）
    if (ladder2Limit.value !== '') {
      const ladder2LimitValue = parseFloat(ladder2Limit.value);
      if (isNaN(ladder2LimitValue) || ladder2LimitValue <= 0) {
        uni.showToast({ title: '第二阶梯用电量上限必须大于0', icon: 'none' });
        return;
      }
      if (ladder2LimitValue <= ladder1LimitValue) {
        uni.showToast({ title: '第二阶梯用电量上限必须大于第一阶梯上限', icon: 'none' });
        return;
      }
      if (ladder2LimitValue > 10000) {
        uni.showToast({ title: '第二阶梯用电量上限不能超过10000千瓦时', icon: 'none' });
        return;
      }
    }
    
    // 日期先后顺序验证
    if (ladderDateStart.value >= ladderDateEnd.value) {
      uni.showToast({ title: '开始日期必须早于结束日期', icon: 'none' });
      return;
    }
    
    type = 'ladder';
    data = {
      type,
      ladder1Limit: ladder1Limit.value,
      ladder1Price: ladder1Price.value,
      ladder2Limit: ladder2Limit.value || '',
      ladder2Price: ladder2Price.value,
      ladder3Price: ladder3Price.value,
      dateStart: ladderDateStart.value,
      dateEnd: ladderDateEnd.value,
    };
  } else {
    uni.showToast({ title: '请先选择一种计价方式', icon: 'none' });
    return;
  }

  // 2. 调用后端接口
  try {
    let requestData = {};
    
    if (type === 'single') {
      // 单一电价接口调用
      requestData = {
        startTime: formatDateForApi(singleDateStart.value, true),
        endTime: formatDateForApi(singleDateEnd.value, false),
        price: parseFloat(singlePrice.value),
      };
      
      const result = await createRequest('/monitor/singleBill', {
        method: 'post',
        data: requestData
      });
      
      resultFee.value = result.data.totalCost.toFixed(2);
      showResult.value = true;
    } else if (type === 'peakvalley') {
      // 峰谷电价接口调用
      const timeRanges = [
        {
          type: 'PEAK',
          price: parseFloat(peakPrice.value),
          startTime: peakStartTime.value,
          endTime: peakEndTime.value
        },
        {
          type: 'VALLEY',
          price: parseFloat(offPeakPrice.value),
          startTime: offPeakStartTime.value,
          endTime: offPeakEndTime.value
        }
      ];
      
      requestData = {
        startTime: formatDateForApi(peakvalleyDateStart.value, true),
        endTime: formatDateForApi(peakvalleyDateEnd.value, false),
        timeRanges: timeRanges
      };
      
      const result = await createRequest('/monitor/peakAndValleyBill', {
        method: 'post',
        data: requestData
      });
      
      resultFee.value = result.data.totalCost.toFixed(2);
      showResult.value = true;
    } else if (type === 'ladder') {
      // 阶梯电价接口调用
      const tiers = [
        {
          usageLimit: parseFloat(ladder1Limit.value),
          price: parseFloat(ladder1Price.value),
        }
      ];
      
      // 如果有第二阶梯上限，则添加第二阶梯
      if (ladder2Limit.value !== '') {
        tiers.push({
          usageLimit: parseFloat(ladder2Limit.value),
          price: parseFloat(ladder2Price.value),
        });
      }
      
      // 添加第三阶梯（无上限）
      tiers.push({
        price: parseFloat(ladder3Price.value),
      });
      
      requestData = {
        startTime: formatDateForApi(ladderDateStart.value, true),
        endTime: formatDateForApi(ladderDateEnd.value, false),
        tiers: tiers
      };
      
      const result = await createRequest('/monitor/stepwiseBill', {
        method: 'post',
        data: requestData
      });
      
      resultFee.value = result.data.totalCost.toFixed(2);
      showResult.value = true;
    }
  } catch (error) {
    uni.showToast({ title: '计算失败', icon: 'none' });
  }
}



// swiper 相关数据
const currentSwiperIndex = ref(0);
const swiperHeight = ref(390);

// 图表数据列表（对应三个时间段）
const chartDataList = ref([
  {
    // 昨日数据 - 蓝色渐变主题
    categories: [],
    series: [
      {
        name: '实际用电量',
        data: [],
        color: '#1890ff',
      },
    ],
    interval: 'yesterday',
    lastFetchTime: 0,
    colors: ['#1890ff', '#1ec8e1', '#66ccff'], // 蓝色渐变主题
    chartOpts: null, // 动态图表配置
  },
  {
    // 上周数据 - 绿色渐变主题
    categories: [],
    series: [
      {
        name: '实际用电量',
        data: [],
        color: '#1890ff',
      },
    ],
    interval: 'lastWeek',
    lastFetchTime: 0,
    colors: ['#52c41a', '#73d13d', '#95de64'], // 绿色渐变主题
    chartOpts: null, // 动态图表配置
  },
  {
    // 上月数据 - 橙色渐变主题
    categories: [],
    series: [
      {
        name: '实际用电量',
        data: [],
        color: '#1890ff',
      },
    ],
    interval: 'lastMonth',
    lastFetchTime: 0,
    colors: ['#fa8c16', '#ffa940', '#ffc069'], // 橙色渐变主题
    chartOpts: null, // 动态图表配置
  },
]);

// 获取图表配置的函数
const getChartOpts = (colors = ['#1890ff']) => {
  return {
    color: colors,
    enableScroll: false,
    legend: {
      show: false,
    },
    xAxis: {
      fontColor: 'rgba(255, 255, 255, 0.3)',
      fontSize: 12,
      data: [{ min: 0, max: 0 }], // 动态设置
      labelCount: 6, // 动态设置
      itemCount: 24, // 动态设置
    },
    yAxis: {
      gridType: 'solid',
      dashLength: 0,
      data: [{ min: 0, max: 100 }], // 动态设置
      fontColor: 'rgba(255, 255, 255, 0.3)',
      fontSize: 16,
      gridColor: 'rgba(255, 255, 255, 0.2)',
      splitNumber: 4,
    },
    extra: {
      line: {
        type: 'curve',
        width: 3,
        activeType: 'hollow',
        linearType: 'custom',
        gradient: true,
        linearOpacity: 0.8,
        linearDirection: 'vertical',
        linearColor: colors, // 使用传入的颜色数组作为渐变色
      },
    },
    dataLabel: false,
    dataPointShape: false,
    enableMarkLine: false,
    enableMarkPoint: false,
  };
};

// 加载状态
const isLoading = ref(false);

// 时间选择器
const timePeriods = [
  { name: '昨日', key: 'yesterday' },
  { name: '上周', key: 'lastWeek' },
  { name: '上月', key: 'lastMonth' },
];
const selectedPeriod = ref(0);







// 获取当前选中时间段的数据
const fetchCurrentPeriodData = async (forceRefresh = false) => {
  const currentPeriodKey = timePeriods[selectedPeriod.value]?.key;
  if (!currentPeriodKey) return;

  // 检查是否已有数据，如果没有数据或强制刷新才请求
  const currentChartData = chartDataList.value[selectedPeriod.value];
  if (!forceRefresh && currentChartData && currentChartData.categories.length > 0) {
    console.log('当前时间段已有数据，跳过请求');
    return;
  }

  isLoading.value = true;
  
  try {
    const result = await createRequest(`/monitor/cumulativePower/${currentPeriodKey}`);
    
    if (result.code === 200 && result.data) {
      // 根据返回的 interval 找到对应的图表索引
      const targetIndex = chartDataList.value.findIndex(item => item.interval === result.data.interval);
      if (targetIndex !== -1) {
        processChartData(result.data, result.data.interval, targetIndex);
        console.log(`成功处理 ${result.data.interval} 时间段的数据，更新图表索引: ${targetIndex}`);
      } else {
        console.warn(`未找到匹配的图表索引，interval: ${result.data.interval}`);
      }
    }
  } catch (error) {
    console.error('获取用电趋势数据失败:', error);
  } finally {
    isLoading.value = false;
  }
};

// swiper 变化事件处理
const handleSwiperChange = (index) => {
  selectedPeriod.value = index;
  const periodName = timePeriods[index]?.name || '未知';
  console.log('Swiper切换到时间段:', periodName, '索引:', index);
  
  // 切换时间段后立即请求数据
  fetchCurrentPeriodData();
};

// 更新后的处理时间段切换函数
const handlePeriodChangeUpdated = async (index) => {
  if (index === selectedPeriod.value) return;
  
  selectedPeriod.value = index;
  currentSwiperIndex.value = index;
  
  const periodName = timePeriods[index]?.name || '未知';
  console.log('时间选择器切换到时间段:', periodName, '索引:', index);
  
  // 切换时间段后立即请求数据
  await fetchCurrentPeriodData();
};

// 处理图表数据
const processChartData = (data, period, index) => {
  // 处理新的数据结构：data.data 包含实际数据
  const actualData = data.data || data;
  const entries = Object.entries(actualData);
  
  if (entries.length === 0) {
    console.warn('没有数据可显示');
    return;
  }
  
  let categories = [];
  let seriesData = [];
  
  // 根据时间段处理数据
  if (period === 'yesterday') {
    // 昨日数据：按小时显示，格式为 "2025-08-17 00:00"
    categories = entries.map(([key]) => {
      const time = key.split(' ')[1]; // 提取时间部分
      const hour = time.substring(0, 2); // 提取小时部分
      return hour.startsWith('0') ? hour.substring(1) : hour; // 去掉前导0
    });
    
    seriesData = entries.map(([, value]) => Math.round(parseFloat(value) || 0));
    
  } else if (period === 'lastWeek' || period === 'lastMonth') {
    // 上周和上月数据：按天显示
    categories = entries.map(([key]) => {
      const date = new Date(key);
      return `${date.getMonth() + 1}/${date.getDate()}`; // 显示为 "8/11"
    });
    
    seriesData = entries.map(([, value]) => Math.round(parseFloat(value) || 0));
  }
  
  // 如果提供了 index，更新 chartDataList
  if (typeof index === 'number' && chartDataList.value[index]) {
    chartDataList.value[index].categories = categories;
    chartDataList.value[index].series[0].data = seriesData;
    chartDataList.value[index].lastFetchTime = Date.now();
    
    // 获取当前图表的配置
    const currentChartOpts = getChartOpts(chartDataList.value[index].colors);
    
    // 动态设置y轴 - 始终从0开始，避免图表偏移
    const maxValue = Math.max(...seriesData);
    
    if (maxValue > 0) {
      currentChartOpts.yAxis.data[0].min = 0;
      currentChartOpts.yAxis.data[0].max = Math.ceil(maxValue + maxValue * 0.1);
    } else {
      // 如果没有数据或所有值都为0，设置默认范围
      currentChartOpts.yAxis.data[0].min = 0;
      currentChartOpts.yAxis.data[0].max = 100;
    }
    
    // 设置x轴
    currentChartOpts.xAxis.data[0].min = 0;
    currentChartOpts.xAxis.data[0].max = Math.max(0, categories.length - 1);
    
    // 根据数据量智能设置标签显示数量
    if (period === 'yesterday') {
      currentChartOpts.xAxis.labelCount = 12;
      currentChartOpts.xAxis.itemCount = 24;
    } else if (period === 'lastWeek') {
      currentChartOpts.xAxis.labelCount = 7;
      currentChartOpts.xAxis.itemCount = 7;
    } else if (period === 'lastMonth') {
      currentChartOpts.xAxis.labelCount = 10;
      currentChartOpts.xAxis.itemCount = categories.length;
    }
    
    // 更新图表配置
    chartDataList.value[index].chartOpts = currentChartOpts;
  }
  

};

// 日期选择器
const showDatePicker = ref(false);
const tempDate = ref('');
const datePickerType = ref('single');
const datePickerWhich = ref('start');
const maxDate = computed(() => {
  const today = new Date();
  return `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(
    2,
    '0'
  )}-${String(today.getDate()).padStart(2, '0')}`;
});
const tempMinDate = ref('');
const tempMaxDate = ref('');

// 时间选择器
const showTimePicker = ref(false);
const tempTime = ref('');
const timePickerType = ref('peak'); // peak/offPeak
const timePickerWhich = ref('start'); // start/end

function openDatePicker(type, which) {
  datePickerType.value = type;
  datePickerWhich.value = which;

  // 动态获取当前类型对应的开始和结束日期
  let startDate, endDate;
  if (type === 'single') {
    startDate = singleDateStart.value;
    endDate = singleDateEnd.value;
  } else if (type === 'peakvalley') {
    startDate = peakvalleyDateStart.value;
    endDate = peakvalleyDateEnd.value;
  } else if (type === 'ladder') {
    startDate = ladderDateStart.value;
    endDate = ladderDateEnd.value;
  }

  if (which === 'start') {
    // 选择开始日期，最大不能超过已选的结束日期
    tempMinDate.value = '2025-01-01';
    tempMaxDate.value = endDate || maxDate.value;
  } else {
    // 选择结束日期，最小不能小于已选的开始日期
    tempMinDate.value = startDate || '2025-01-01';
    tempMaxDate.value = maxDate.value;
  }

  // 确保最小日期不超过最大日期
  if (tempMinDate.value > tempMaxDate.value) {
    uni.showToast({ title: '日期范围不合法', icon: 'none' });
    return;
  }

  showDatePicker.value = true;
}
function onDateConfirm(val) {
  // 统一日期格式为YYYY-MM-DD
  const dateVal = val.replace(/\//g, '-');
  let min = tempMinDate.value;
  let max = tempMaxDate.value;
  // 兜底校验：如果选中日期不在范围内，自动修正并提示
  if (min && dateVal < min) {
    uni.showToast({ title: `日期不能早于${min}`, icon: 'none' });
    // 自动修正为min
    setDateValue(min);
    showDatePicker.value = false;
    return;
  }
  if (max && dateVal > max) {
    uni.showToast({ title: `日期不能晚于${max}`, icon: 'none' });
    // 自动修正为max
    setDateValue(max);
    showDatePicker.value = false;
    return;
  }
  setDateValue(dateVal);
  showDatePicker.value = false;
}

function setDateValue(dateVal) {
  if (datePickerType.value === 'single') {
    if (datePickerWhich.value === 'start') {
      singleDateStart.value = dateVal;
    } else {
      singleDateEnd.value = dateVal;
    }
  } else if (datePickerType.value === 'peakvalley') {
    if (datePickerWhich.value === 'start') {
      peakvalleyDateStart.value = dateVal;
    } else {
      peakvalleyDateEnd.value = dateVal;
    }
  } else if (datePickerType.value === 'ladder') {
    if (datePickerWhich.value === 'start') {
      ladderDateStart.value = dateVal;
    } else {
      ladderDateEnd.value = dateVal;
    }
  }
}

// 打开时间选择器
function openTimePicker(type, which) {
  timePickerType.value = type;
  timePickerWhich.value = which;
  
  // 设置当前时间值
  if (type === 'peak') {
    tempTime.value = which === 'start' ? peakStartTime.value : peakEndTime.value;
  } else if (type === 'offPeak') {
    tempTime.value = which === 'start' ? offPeakStartTime.value : offPeakEndTime.value;
  }
  
  showTimePicker.value = true;
}

// 时间选择器确认
function onTimeConfirm(val) {
  setTimeValue(val);
  showTimePicker.value = false;
}

// 设置时间值
function setTimeValue(timeVal) {
  if (timePickerType.value === 'peak') {
    if (timePickerWhich.value === 'start') {
      peakStartTime.value = timeVal;
    } else {
      peakEndTime.value = timeVal;
    }
  } else if (timePickerType.value === 'offPeak') {
    if (timePickerWhich.value === 'start') {
      offPeakStartTime.value = timeVal;
    } else {
      offPeakEndTime.value = timeVal;
    }
  }
}

onMounted(() => {
  // 初始化所有时间段的数据
  fetchCurrentPeriodData();
});
</script>

<style scoped lang="scss">
.electricity-calc {
  padding: 20rpx;
  box-sizing: border-box;
}
.calc-section {
  background: none;
  margin-bottom: 30rpx;
}
.section-title {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 690rpx;
  height: 88rpx;
  background-image: url('/static/img/components/section-title.png');
  background-size: 100% 100%;
  background-repeat: no-repeat;
  background-position: center;
  font-size: 36rpx;
  font-weight: bold;
  color: #fff;
  letter-spacing: 3rpx;
}
.card-list {
  width: 690rpx;
  display: flex;
  flex-direction: column;
  gap: 30rpx;
  padding: 36rpx 30rpx 20rpx;
  box-sizing: border-box;
  border-left: 1rpx solid #1ec8e1;
  border-right: 1rpx solid #1ec8e1;
  background: linear-gradient(to bottom, #0b317f 0%, #051844 100%);
  position: relative;
  margin-bottom: 40rpx;
  align-items: center;
  transition: height 0.3s cubic-bezier(0.25, 0.46, 0.45, 0.94); /* 添加高度过渡效果 */
}
.table-bottom {
  position: absolute;
  bottom: -12rpx;
  left: -6rpx;
  width: 700rpx;
}

.calc-card {
  border-radius: 0;
  overflow: hidden;
  position: relative;
  width: 100%;
  min-height: 64rpx; /* 卡片头部高度 */
}
.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 64rpx;
  background: rgba(255, 255, 255, 0.14);
  position: relative;
  font-size: 28rpx;
  color: #fff;
  padding: 0 20rpx;
  box-sizing: border-box;
}
.card-icon {
  margin-right: 16rpx;
  width: 28rpx;
  height: 28rpx;
  pointer-events: none;
}
.card-title {
  flex: 1;
}
.card-arrow {
  width: 24rpx;
  height: 24rpx;
  pointer-events: none;
}
.card-body {
  padding: 32rpx 24rpx 24rpx 24rpx;
  background: rgba(255, 255, 255, 0.08);
  transform-origin: top;
  will-change: transform;
}
.form-row {
  display: flex;
  align-items: center;
  margin-bottom: 18rpx;
  gap: 16rpx;
}
.form-label {
  width: 80rpx;
  font-size: 22rpx;
  color: #b8cfff;
}
.form-input {
  height: 56rpx;
  background: #1a3a6a;
  border: 1rpx solid #2a4a7a;
  border-radius: 8rpx;
  padding: 0 16rpx;
  font-size: 20rpx;
  color: #fff;
  box-sizing: border-box;
  &::placeholder {
    color: rgba(255, 255, 255, 0.6);
  }
}

// 阶梯电价专用样式
.ladder-row {
  display: flex;
  align-items: center;
  margin-bottom: 18rpx;
  gap: 16rpx;
}

.ladder-label {
  width: 120rpx;
  font-size: 22rpx;
  color: #fff;
  flex-shrink: 0;
}

.ladder-input {
  flex: 1;
  height: 56rpx;
  background: rgba(255, 255, 255, 0.1);
  border: none;
  border-radius: 4rpx;
  padding: 0 16rpx;
  font-size: 20rpx;
  color: #fff;
  box-sizing: border-box;
  &::placeholder {
    color: rgba(255, 255, 255, 0.6);
  }
}

.result-modal-mask {
  position: fixed;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  z-index: 9999;
  display: flex;
  align-items: center;
  justify-content: center;
}
.result-modal {
  background: linear-gradient(135deg, #0f2a5a 0%, #071E51 100%);
  border-radius: 40rpx;
  padding: 60rpx 40rpx 40rpx 40rpx;
  width: 600rpx;
  min-height: 600rpx;
  box-shadow: 0 16rpx 48rpx rgba(30, 200, 225, 0.3);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-between;
  position: relative;
  overflow: hidden;
}

.result-modal::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(135deg, rgba(30, 200, 225, 0.1) 0%, transparent 50%);
  pointer-events: none;
}
.result-icon-container {
  position: relative;
  margin-bottom: 40rpx;
  z-index: 1;
}

.result-icon-glow {
  position: absolute;
  left: 50%;
  transform: translate(-50%, -10%) scale(1.1);
  width: 360rpx;
  z-index: 2;
  filter: drop-shadow(0 0 20rpx rgba(30, 200, 225, 0.8));
}

@keyframes glow {
  from {
    transform: translate(-50%, -50%) scale(1);
    opacity: 0.6;
  }
  to {
    transform: translate(-50%, -50%) scale(1.2);
    opacity: 1;
  }
}
.result-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  text-align: center;
  z-index: 1;
  margin-top: 160rpx;
}

.result-main-text {
  color: rgba(255, 255, 255, 0.9);
  font-size: 28rpx;
  margin-bottom: 20rpx;
  line-height: 1.4;
}

.result-amount {
  color: #1ec8e1;
  font-size: 48rpx;
  font-weight: bold;
  margin-bottom: 30rpx;
  text-shadow: 0 0 10rpx rgba(30, 200, 225, 0.5);
}

.result-detail-text {
  color: rgba(255, 255, 255, 0.8);
  font-size: 24rpx;
  line-height: 1.6;
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}

.detail-amount {
  color: #1ec8e1;
  font-weight: bold;
  font-size: 28rpx;
}
.result-btn {
  background: linear-gradient(135deg, #1ec8e1 0%, #1890ff 100%);
  color: #fff;
  border-radius: 12rpx;
  font-size: 28rpx;
  padding: 20rpx 60rpx;
  font-weight: bold;
  cursor: pointer;
  box-shadow: 0 4rpx 16rpx rgba(30, 200, 225, 0.3);
  transition: all 0.3s ease;
  z-index: 1;
  min-width: 200rpx;
  text-align: center;
}

.result-btn:active {
  transform: scale(0.95);
  box-shadow: 0 2rpx 8rpx rgba(30, 200, 225, 0.4);
}
.calc-section {
  background: none;
  margin-bottom: 30rpx;
}

.trend-section {
  width: 686rpx;
  background-image: url('/static/img/components/chart-section.png');
  background-size: 100% 100%;
  background-repeat: no-repeat;
  background-position: center;
  overflow: hidden;
  padding-bottom: 20rpx;
}

.section-title-chart {
  width: 100%;
  height: 68rpx;
  background-image: url('/static/img/homePages/chart-title.png');
  background-size: 100% 100%;
}

.chart-title-text {
  font-size: 36rpx;
  color: #fff;
  letter-spacing: 3rpx;
  font-family: 'YouSheBiaoTiHei';
  line-height: 68rpx;
  margin-left: 60rpx;
}

// 表单样式
.calc-form {
  padding: 30rpx;
}

.form-item {
  display: flex;
  align-items: center;
  margin-bottom: 24rpx;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #1a3a6a;

  &:last-child {
    border-bottom: none;
  }
}

.form-label {
  width: 200rpx;
  font-size: 24rpx;
  color: #fff;
  font-weight: 500;
  flex-shrink: 0;
}

.form-input {
  flex: 1;
  height: 60rpx;
  background: #1a3a6a;
  border: 1rpx solid #2a4a7a;
  border-radius: 8rpx;
  padding: 0 20rpx;
  font-size: 22rpx;
  color: #fff;
  box-sizing: border-box;

  &::placeholder {
    color: rgba(255, 255, 255, 0.6);
  }

  &.result-input {
    background: #2a4a7a;
    border-color: #1ec8e1;
    color: #1ec8e1;
    font-weight: bold;
  }
}

.calc-button {
  background: linear-gradient(90deg, #1ec8e1 0%, #1890ff 100%);
  color: white;
  text-align: center;
  padding: 20rpx;
  box-sizing: border-box;
  border-radius: 12rpx;
  font-size: 28rpx;
  font-weight: bold;
  transition: all 0.3s ease;
  margin-top: -10rpx;
  width: 100%;
  letter-spacing: 4rpx;
}

.calc-button:active {
  transform: scale(0.98);
  box-shadow: 0 2rpx 8rpx rgba(24, 144, 255, 0.3);
}

.chart-header-container {
  width: 100%;
  height: 86rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

// 时间选择器样式
.time-selector {
  position: relative;
  display: flex;
  padding: 30rpx;
  align-items: center;
  justify-content: space-evenly;
  box-sizing: border-box;
  width: 400rpx;
  margin: 20rpx auto 0;
}

.time-tab {
  flex: 1;
  text-align: center;
  transition: all 0.3s ease;
  padding: 0 8rpx;
  background-color: rgba($color: #fff, $alpha: 0.1);
  min-width: 88rpx;
  margin-right: 8rpx;
  border-radius: 4rpx;
  height: 32rpx;
  line-height: 32rpx;
  text-align: center;
}

.time-tab.active {
  background: linear-gradient(180deg, #1a3a6a 0%, #0f2a5a 100%);
  border-color: #1ec8e1;
}

.time-text {
  font-size: 20rpx;
  color: rgba($color: #fff, $alpha: 0.5);
}

.time-tab.active .time-text {
  color: #096bda;
}
.chart-header-title {
  flex: 1;
  padding: 30rpx;
  box-sizing: border-box;
}

// 图例样式
.chart-legend {
  flex: 1;
  display: flex;
  padding: 30rpx;
  box-sizing: border-box;
  align-items: center;
  justify-content: flex-end;
}

.legend-item {
  display: flex;
  align-items: center;
}

.legend-color {
  width: 10rpx;
  height: 10rpx;
  background: #1890ff;
  border-radius: 4rpx;
  margin-right: 12rpx;
  margin-top: 6rpx;
}

.legend-text {
  font-size: 20rpx;
  color: rgba($color: #fff, $alpha: 0.8);
}

// 图表容器
.chart-container {
  transform: scale(1);
  height: 390rpx;
  width: 100%;
}

// swiper 相关样式
.chart-item {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.no-data-tip {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  width: 100%;
}

.no-data-text {
  color: rgba(255, 255, 255, 0.6);
  font-size: 24rpx;
}

.card-body {
  padding: 32rpx 24rpx 24rpx 24rpx;
  background: rgba(255, 255, 255, 0.08);
  transform-origin: top;
  will-change: transform;
  transition: all 0.3s ease;
  max-height: 1000rpx;
  opacity: 1;
  transform: scaleY(1);
  overflow: hidden;
}

.card-body.collapsed {
  max-height: 0;
  opacity: 0;
  transform: scaleY(0);
  padding-top: 0;
  padding-bottom: 0;
}
.detail-calendar {
  box-sizing: border-box;
  color: #eee;
  // 参考consoleView的日期选择器样式
}

:deep(.tn-popup__content) {
  background-color: #1F3462 !important;
}

:deep(.uni-picker-view-mask) {
  background: transparent !important;
}

:deep(.tn-calendar__data) {
  box-sizing: border-box !important;
}

:deep(.tn-calendar__week-text) {
  box-sizing: border-box !important;
}

:deep(.tn-calendar__operation) {
  box-sizing: border-box !important;
}
.date-picker-container {
  background: #fff;
  border-radius: 32rpx 32rpx 0 0;
  overflow: hidden;
}
.date-picker-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
}
.date-picker-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}
.date-picker-actions {
  display: flex;
  gap: 20rpx;
}
.action-btn {
  font-size: 28rpx;
  color: #666;
  padding: 8rpx 16rpx;
  &.confirm {
    color: #1ec8e1;
    font-weight: 500;
  }
}
// 电价输入区域
.price-input-section {
  margin-bottom: 32rpx;
}

.price-label {
  display: block;
  font-size: 24rpx;
  color: #fff;
  margin-bottom: 16rpx;
  font-weight: 500;
}

.price-input {
  width: 100%;
  height: 80rpx;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 4rpx;
  padding: 0 24rpx;
  font-size: 24rpx;
  color: #fff;
  box-sizing: border-box;

  &::placeholder {
    color: rgba(255, 255, 255, 0.6);
  }
}

// 日期区间选择区域
.date-range-section {
  display: flex;
  gap: 20rpx;
}

.date-input-group {
  flex: 1;
  position: relative;
  display: flex;
  align-items: center;
}

.date-input {
  flex: 1;
  height: 52rpx;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 4rpx;
  padding: 0 24rpx;
  font-size: 24rpx;
  color: #fff;
  display: flex;
  align-items: center;
}

.calendar-icon {
  position: absolute;
  right: 16rpx;
  width: 20rpx;
  height: 20rpx;
  pointer-events: none;
}

// 峰值电价区域
.peak-price-section {
  margin-bottom: 32rpx;
}

.time-range-section {
  display: flex;
  gap: 20rpx;
  margin-top: 16rpx;
}

.last-time-section {
  margin-bottom: 20rpx;
}

.time-input-group {
  flex: 1;
  position: relative;
  display: flex;
  align-items: center;
}

.time-input {
  flex: 1;
  height: 52rpx;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 4rpx;
  padding: 0 24rpx;
  font-size: 24rpx;
  color: #fff;
  display: flex;
  align-items: center;
}

.time-icon {
  position: absolute;
  right: 16rpx;
  width: 20rpx;
  height: 20rpx;
  pointer-events: none;
}


.form-date-text {
  min-width: 120rpx;
  padding: 0 16rpx;
  height: 56rpx;
  line-height: 56rpx;
  background: #1a3a6a;
  border: 1rpx solid #2a4a7a;
  border-radius: 8rpx;
  font-size: 20rpx;
  color: #fff;
  margin-right: 12rpx;
  cursor: pointer;
  display: inline-block;
  text-align: center;
  transition: border-color 0.2s;
  &:last-child {
    margin-right: 0;
  }
  &:hover {
    border-color: #1ec8e1;
    color: #1ec8e1;
  }
}
</style>
